//
//  ViewController.m
//  MgsDemo
//
//  Created by zgy on 2025/2/26.
//

#import "ViewController.h"
#include "mongoose.h"

#import <WebKit/WebKit.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor orangeColor];
    
    
    WKPreferences *pr = [WKPreferences new];
    pr.javaScriptCanOpenWindowsAutomatically = YES;
    
    
    WKWebViewConfiguration *cfg = [WKWebViewConfiguration new];
    cfg.allowsInlineMediaPlayback = YES;
    cfg.preferences = pr;
    cfg.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll;
    
    
    WKWebView *webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:cfg];
    [self.view addSubview:webview];
    
    NSURL *url = [NSURL URLWithString:@"http://localhost:8090"];
//    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];
    
    
//    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"WebRoot" ofType:@"bundle"]];
//    NSString *path = [bundle pathForResource:@"web_root" ofType:nil];
//    NSLog(@"%@", path);
    
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        struct mg_mgr mgr;  // Declare event manager
        mg_mgr_init(&mgr);  // Initialise event manager
        mg_http_listen(&mgr, "http://0.0.0.0:8090", ev_handler, NULL);  // Setup listener
        for (;;) {          // Run an infinite event loop
            mg_mgr_poll(&mgr, 1000);
        }
    });
     
    
}


// HTTP server event handler function
void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
    if (ev == MG_EV_HTTP_MSG) {
        struct mg_http_message *hm = (struct mg_http_message *) ev_data;
        NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"WebRoot" ofType:@"bundle"]];
        const char *path = [[bundle pathForResource:@"web_root" ofType:nil] UTF8String];
        
        struct mg_http_serve_opts opts = { .root_dir = path };
        mg_http_serve_dir(c, hm, &opts);
    }
}



@end
